<?php

namespace App\Http\Controller\AdminPort;

use App\Core\Annotation\NoNeedLogin;
use App\Core\AppKey;
use App\Model\AuthAccountModel;
use App\Model\EmployeeModel;
use App\Service\AuthAccountService;
use App\Service\FileService;
use Hyperf\Di\Annotation\Inject;
use Lhp\JigsawPuzzleVerify\Verify;


/**
 * 登录授权
 * @package App\Http\Controller\AdminPort
 */
class Auth
{
    #[Inject]
    protected AuthAccountService $authAccountService;

    #[Inject]
    protected Verify $verify;

    #[Inject]
    protected FileService $fileService;

    /**
     * 登录
     * @return string[]
     */
    #[NoNeedLogin]
    public function get()
    {
        AuthAccountModel::validateColumn(
            [],
            [
                AuthAccountModel::C_ACCOUNT,
                AuthAccountModel::C_PASSWORD
            ]
        );

        $account = I(AuthAccountModel::C_ACCOUNT);
        $errorNumber = $this->authAccountService->getLoginAccoountInputErrorNumber(1, 1, $account);
        if ($errorNumber > 2) {
            $this->verifyCaptcha();
        }

        $data = $this->authAccountService->getTokenByPassword(1, 1, 1, I(AuthAccountModel::C_ACCOUNT),
            I(AuthAccountModel::C_PASSWORD), getClientIp(), 'pc');
        return getResponseData('', $data);
    }

    /**
     *  获取登录人详细信息
     * @return string[]
     */
    public function getUser()
    {
        $data = authUser()->getAttributesInClumns([
            'user_id',
            EmployeeModel::C_PORTRAIT,
            EmployeeModel::C_COMPANY_ID,
            'name',
            'reset_password_number',
            'permissions'
        ]);

        $data['permissions'][] = 'home-dashboard';
        $data['permissions'][] = 'home-usercenter';
        $data['portrait'] = $this->fileService->getUrl($data['portrait']);
        return getResponseData('', $data);
    }

    /**
     * 图形验证验证
     * @return  void
     */
    protected function verifyCaptcha()
    {
        validate([
            ['标识key', 'captchaKey', 'required|string|max:500'],
            ['截图位置', 'captchaX', 'required|number|min:0|max:500']
        ]);

        try {
            if ( ! $this->verify->verify(I('captchaKey'), I('captchaX'))) {
                responseError('验证失败');
            }
        } catch (\Exception $e) {
            responseError('验证过期，请重新验证');
        }
    }

    /**
     * 刷新
     * @return array
     */
    #[NoNeedLogin]
    public function updateRefresh()
    {
        $token = getContext(AppKey::CONTEXT_HTTP_AUTH_TOKEN);
        if ( ! $token) {
            responseError('token不能为空');
        }

        $data = $this->authAccountService->refreshToken($token);
        return getResponseData('', $data);
    }

    /**
     * 刷新
     * @return array
     */
    public function updatePassword()
    {
        try {
            AuthAccountModel::validateColumn(
                [],
                [
                    AuthAccountModel::C_PASSWORD
                ]
            );
        } catch (\Exception $e) {
            responseError('新密码格式错误');
        }

        try {
            AuthAccountModel::validateColumn(
                [],
                [
                    AuthAccountModel::C_PASSWORD
                ],
                false,
                [
                    AuthAccountModel::C_PASSWORD => 'oldPassowrd'
                ]
            );
        } catch (\Exception $e) {
            responseError('旧密码格式错误');
        }

        $this->authAccountService->updatePasswordByOldPassword(
            authUser()->id, I('oldPassowrd'), I(AuthAccountModel::C_PASSWORD));
        return getResponseData('修改成功');
    }
}
